<template>
  <el-container class="trade-container">
    <el-header class="header-style">
      <div class="header-content">
        <h2>交易管理</h2>
        <div class="button-group">
          <el-button type="primary" @click="openDialog">新增交易</el-button>
          <el-button type="success" @click="downloadExcel">下载Excel</el-button>
        </div>
      </div>
    </el-header>
    <el-main class="main-style">
      <el-table :data="tradeData" border style="width: 100%">
        <el-table-column prop="tradeID" label="ID"></el-table-column>
        <el-table-column prop="cardID" label="卡号"></el-table-column>
        <el-table-column prop="tradeMoney" label="交易金额"></el-table-column>
        <el-table-column prop="tradeDate" label="交易日期"></el-table-column>
        <el-table-column prop="tradeType" label="交易类型"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 交易可视化图表 -->
      <div class="chart-container">
        <el-card>
          <template #header>
            <div class="chart-header">
              <h3>交易趋势分析</h3>
              <div class="chart-actions">
                <el-select v-model="chartType" @change="updateChart">
                  <el-option label="折线图" value="line"></el-option>
                  <el-option label="柱状图" value="bar"></el-option>
                  <el-option label="饼图" value="pie"></el-option>
                </el-select>
              </div>
            </div>
          </template>
          <div ref="chartRef" style="width: 100%; height: 400px;"></div>
        </el-card>
      </div>
    </el-main>
  </el-container>

  <!-- 新增/编辑交易对话框 -->
  <el-dialog v-model="dialogVisible" :title="editMode ? '编辑交易' : '新增交易'">
    <el-form :model="tradeForm">
      <el-form-item label="卡号">
        <el-input v-model="tradeForm.cardID" placeholder="请输入卡号"></el-input>
      </el-form-item>
      <el-form-item label="交易金额">
        <el-input v-model="tradeForm.tradeMoney" placeholder="请输入交易金额"></el-input>
      </el-form-item>
      <el-form-item label="交易日期">
        <el-date-picker v-model="tradeForm.tradeDate" type="date" placeholder="选择日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="交易类型">
        <el-select v-model="tradeForm.tradeType" placeholder="请选择交易类型">
          <el-option label="存款" value="存款"></el-option>
          <el-option label="取款" value="取款"></el-option>
          <el-option label="转账" value="转账"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="tradeForm.remark" placeholder="请输入备注"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitTrade">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import * as XLSX from 'xlsx';

export default {
  name: 'TradeView',
  setup() {
    const tradeData = ref([]);
    const dialogVisible = ref(false);
    const editMode = ref(false);
    const currentRow = ref(null);
    const tradeForm = ref({
      cardID: '',
      tradeMoney: '',
      tradeDate: '',
      tradeType: '',
      remark: '',
    });
    const chartRef = ref(null);
    const chartType = ref('line');
    let chartInstance = null;

    // 从后端获取交易数据
    const fetchTrades = async () => {
      try {
        const response = await axios.get('http://localhost:8088/api/transactions');
        tradeData.value = response.data;
        initializeChart();
      } catch (error) {
        console.error('获取交易数据失败:', error);
      }
    };

    // 初始化图表
    const initializeChart = () => {
      if (!chartInstance && chartRef.value) {
        // chartInstance = echarts.init(chartRef.value);
        updateChart();
      }
    };

    // 更新图表数据和类型
    const updateChart = () => {
      if (!chartInstance) return;

      const option = {
        title: {
          text: '交易趋势分析',
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: ['交易金额'],
        },
        xAxis: {
          type: 'category',
          data: tradeData.value.map(item => item.tradeDate),
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} 元',
          },
        },
        series: [
          {
            name: '交易金额',
            type: chartType.value,
            data: tradeData.value.map(item => parseFloat(item.tradeMoney)),
            smooth: chartType.value === 'line',
          },
        ],
      };

      chartInstance.setOption(option);
    };

    // 生命周期钩子：组件挂载后获取交易数据
    onMounted(() => {
      fetchTrades();
      window.addEventListener('resize', () => {
        if (chartInstance) {
          chartInstance.resize();
        }
      });
    });

    const handleEdit = (index, row) => {
      editMode.value = true;
      currentRow.value = row;
      tradeForm.value = { ...row };
      dialogVisible.value = true;
    };

    const handleDelete = (index, row) => {
      axios.delete(`http://localhost:8088/api/transactions/delete/${row.tradeID}`)
          .then(response => {
            console.log('删除交易成功:', response.data);
            tradeData.value = tradeData.value.filter(item => item.tradeID !== row.tradeID);
            updateChart();
          })
          .catch(error => {
            console.error('删除交易失败:', error);
          });
    };

    const openDialog = () => {
      editMode.value = false;
      currentRow.value = null;
      tradeForm.value = { cardID: '', tradeMoney: '', tradeDate: '', tradeType: '', remark: '' };
      dialogVisible.value = true;
    };

    const submitTrade = () => {
      if (editMode.value && currentRow.value) {
        axios.put('http://localhost:8088/api/transactions/update', { ...tradeForm.value, tradeID: currentRow.value.tradeID })
            .then(response => {
              console.log('更新交易成功:', response.data);
              const index = tradeData.value.findIndex(item => item.tradeID === currentRow.value.tradeID);
              if (index !== -1) {
                tradeData.value[index] = { ...tradeForm.value, tradeID: currentRow.value.tradeID };
              }
              updateChart();
            })
            .catch(error => {
              console.error('更新交易失败:', error);
            });
      } else {
        axios.post('http://localhost:8088/api/transactions/insert', tradeForm.value)
            .then(response => {
              console.log('新增交易成功:', response.data);
              const newId = response.data.insertedId || (tradeData.value.length > 0 ? Math.max(...tradeData.value.map(item => item.tradeID)) + 1 : 1);
              tradeData.value.push({ tradeID: newId, ...tradeForm.value });
              updateChart();
            })
            .catch(error => {
              console.error('新增交易失败:', error);
            });
      }
      dialogVisible.value = false;
    };

    // 下载Excel
    const downloadExcel = () => {
      const workbook = XLSX.utils.book_new();
      const worksheet = XLSX.utils.json_to_sheet(tradeData.value);
      XLSX.utils.book_append_sheet(workbook, worksheet, '交易信息');
      XLSX.writeFile(workbook, '交易信息.xlsx');
    };

    return {
      tradeData,
      dialogVisible,
      editMode,
      currentRow,
      tradeForm,
      chartRef,
      chartType,
      handleEdit,
      handleDelete,
      openDialog,
      submitTrade,
      downloadExcel,
    };
  },
};
</script>

<style scoped>
.trade-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header-style {
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 10px 20px;
  position: sticky;
  top: 0;
  z-index: 99;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  flex: 1;
  justify-content: space-between;
  align-items: center;
}

.main-style {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.el-table {
  height: 100%;
}

.button-group {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.chart-container {
  margin-top: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-actions {
  display: flex;
  gap: 10px;
}
</style>